package com.homedo.async.mysql.support.prepare.delete;

import com.blinkfox.zealot.bean.SqlInfo;
import com.blinkfox.zealot.core.ZealotKhala;
import com.google.common.collect.Lists;
import com.homedo.async.mysql.support.meta.EntityMetaData;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author jgshun
 * @date 2020/3/5 1:56 PM
 */
public abstract class RecordId2Sql4Delete {

    public static <T, ID> Object[] prepare(EntityMetaData<T> entityMetaData, Iterable<ID> ids) {
        Field primaryKeyField = entityMetaData.getPrimaryKeyField();
        if (primaryKeyField == null) {
            throw new RuntimeException("[主键不存在:" + entityMetaData.getEntityClazs() + "]");
        }

        Object[] prepareSelectSql = new Object[2];

        ZealotKhala sqlKhala = ZealotKhala.start()
                .deleteFrom(entityMetaData.getTableName());

        String columnName = entityMetaData.getFieldColumNameMapping().get(primaryKeyField).toString();

        List idList = Lists.newArrayList(ids);

        sqlKhala.where(" ");

        if (idList.size() == 1) {
            sqlKhala.equal(columnName, idList.get(0));
        } else {
            sqlKhala.in(columnName, idList);
        }

        SqlInfo sqlInfo = sqlKhala.end();

        prepareSelectSql[0] = sqlInfo.getSql();
        prepareSelectSql[1] = sqlInfo.getParams();

        return prepareSelectSql;
    }

}

